<template>
	<view class="container">
		<view>
			<view class="swiper-box" v-if='pictures'>
				<u-swiper :list="pictures" :height='swiperHeight'></u-swiper>
			</view>
		</view>

		<!-- 产品信息区域 -->
		<view class="info-section">
			<view class="product-name">{{ product.name }}</view>
			<!-- 产品标签 -->
			<view v-if='product.tags && product.tags.length > 0'>
				<scroll-view
				   scroll-x 
				   class="scroll-container"
				   :show-scrollbar="false"
				   enable-flex
				 >
				   <!-- 使用flex布局强制所有元素在一行 -->
				   <view class="tag-container">
				     <text v-for='tag in product.tags' @click="toUrl(`/pages/product/search?tag=${tag.id}&category=0`)" class="tag-item" >{{tag.__toString}}</text>
				   </view>
				 </scroll-view>
			</view>
			<view class="product-price">
				<text class="price-symbol">¥</text>
				<text class="price-number">{{ choosedSpec.__metadata.price }}</text>
			</view>
		</view>

		
		<!-- 产品详情内容 -->
		<view class="detail-section">
			<view style='padding:10px 0px 0px 10px'>
				<view class="section-title;">产品详情</view>
			</view>

			<view v-if='product.manufacturingLicenseNumber' style='padding:0px 8px 10px 8px;font-size:12px;'>
				<view class="form-table">

					<!-- 表单内容 -->
					<u-row class="data-row">
						<!-- 第1列：带底色的字段标签 -->
						<u-col span="2" class="label-cell bg-cell">
							生产日期
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.manufacturingDate ? product.manufacturingDate : '见包装'}}
						</u-col>
						<u-col span="2" class="label-cell bg-cell">
							<view>生产许可</view>
							<view>证编号</view>

						</u-col>
						<u-col span="4" class="value-cell">
							{{product.manufacturingLicenseNumber ? product.manufacturingLicenseNumber : ''}}
						</u-col>
					</u-row>
					<view style='padding:5px 0px;'>
						<u-line></u-line>
					</view>
					<u-row class="data-row">
						<!-- 第1列：带底色的字段标签 -->
						<u-col span="2" class="label-cell bg-cell">
							<view>产品</view>
							<view>标准号</view>
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.productStandardNumber ? product.productStandardNumber : ''}}
						</u-col>
						<u-col span="2" class="label-cell bg-cell">
							厂名
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.factoryName ? product.factoryName : ''}}
						</u-col>
					</u-row>
					<view style='padding:5px 0px;'>
						<u-line></u-line>
					</view>
					<u-row class="data-row">
						<!-- 第1列：带底色的字段标签 -->
						<u-col span="2" class="label-cell bg-cell">
							厂址
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.factoryAddress ? product.factoryAddress : ''}}
						</u-col>
						<u-col span="2" class="label-cell bg-cell">
							联系方式
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.manufacturerContactInformation ? product.manufacturerContactInformation : ''}}
						</u-col>
					</u-row>
					<view style='padding:5px 0px;'>
						<u-line></u-line>
					</view>
					<u-row class="data-row">
						<!-- 第1列：带底色的字段标签 -->
						<u-col span="2" class="label-cell bg-cell">
							配料表
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.ingredientList ? product.ingredientList : ''}}
						</u-col>
						<u-col span="2" class="label-cell bg-cell">
							储藏方法
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.storageMethod ? product.storageMethod : ''}}
						</u-col>
					</u-row>
					<view style='padding:5px 0px;'>
						<u-line></u-line>
					</view>
					<u-row class="data-row">
						<!-- 第1列：带底色的字段标签 -->
						<u-col span="2" class="label-cell bg-cell">
							保质期
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.shelfLife ? product.shelfLife : ''}}
						</u-col>
						<u-col span="2" class="label-cell bg-cell">
							食品添加剂
						</u-col>
						<u-col span="4" class="value-cell">
							{{product.foodAdditives ? product.foodAdditives : ''}}
						</u-col>
					</u-row>
					<view style='padding:5px 0px;'>
						<u-line></u-line>
					</view>
				</view>
			</view>

			<u-parse :content="product.description"></u-parse>
		</view>

		<!-- 底部操作栏 -->
		<view class="action-bar">
			<button class="action-button" open-type="share" hover-class="none">
				<u-icon name="share" size="24"></u-icon>
				<text>分享</text>
			</button>
			<view class="action-button" @click="toggleFavorite">
				<u-icon :name="isFavorite ? 'heart-fill' : 'heart'"
					:color="isFavorite ? '#f56c6c' : '#606266'"></u-icon>
				<text>收藏</text>
			</view>
			<view class="buy-button" @click="show = true">
				<text>购买</text>
			</view>
		</view>

		<u-popup :show="show" @close="show = false" mode='bottom'>
			<view class='add-view'>
				<view class="product">
					<view class='activity-item'>
						<image class="product-img" :src="product.cover" mode="aspectFit"></image>
						<view class="product-info">
							<view class="product-name">{{ product.name }}</view>
							<view>
								<text class='category-name'>
									{{product.category.__toString}}
								</text>
							</view>
							<view class="product-price">¥{{ choosedSpec.__metadata.price }}</view>
						</view>
					</view>
				</view>
				<view>
					<view style='padding:10px;font-size:16px;color:#303133'>
						规格
					</view>
					<view>
						<u-row>
							<u-col :span='3' v-for='item in product.specifications'>
								<view v-if='choosedSpec.id == item.id' class='spec-active'>
									{{ item.__metadata.name }}
								</view>
								<view v-else class='spec' @click='choosedSpec = item'>
									{{ item.__metadata.name }}
								</view>
							</u-col>
						</u-row>
					</view>
					<view>
						<u-row>
							<u-col span='6'>
								<view style='margin-top:20px;padding-left: 10px;font-size: 20px;color:#606266'>
									数量：
								</view>
							</u-col>
							<u-col span='6'>
								<view style='margin-top:20px;float:right;margin-right: 20px;'>
									<u-number-box v-model="quantity" @change="changeQuantity"></u-number-box>
								</view>
							</u-col>
						</u-row>
					</view>
					<!-- 加购产品 -->
					<view>
						<view v-if='exchangeProducts && exchangeProducts.length > 0' style='margin-bottom: 50rpx;'>
							<view style='margin:10px'>
								<u-divider text="超值换购"></u-divider>
							</view>
							<view>
								<view class="e-container">
									<scroll-view scroll-x class="e-scroll-view" :show-scrollbar="false">
										<view class="e-goods-list">
											<view v-for="(item, index) in exchangeProducts" :key="index"
												class="e-goods-item">
												<view class="e-image-container"
													@click='toUrl(`/pages/product/detail?id=${item.id}`)'>
													<image :src="item.cover" mode="aspectFill"
														class="e-product-image" />
												</view>

												<view class="e-info">
													<text class="e-name"
														@click='toUrl(`/pages/product/detail?id=${item.id}`)'>{{ item.name }}</text>
													<text
														class="e-price">¥{{ item.specifications[0].__metadata.price }}</text>
												</view>
												<view>
													<u-row>
														<u-col span='12'>
															<view>
																<u-number-box v-model="item.quantity"
																	min='0'></u-number-box>
															</view>
														</u-col>
													</u-row>
												</view>
											</view>
										</view>
									</scroll-view>
								</view>
							</view>
						</view>
						<view v-else style='margin-bottom: 10rpx;'>

						</view>
					</view>
				</view>
				<view class='footer'>
					<view>
						<u-row>
							<u-col span='4'>
								<view class='price'>
									￥{{totalPrice}}
								</view>
							</u-col>
							<u-col span='4'>
								<view>
									<u-button type='success' text='加入购物车' @click='addCart'></u-button>
								</view>
							</u-col>
							<u-col span='4'>
								<view>
									<u-button type='warning' text='直接购买' @click='buyNow'></u-button>
								</view>
							</u-col>
						</u-row>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				product: '',
				isFavorite: false,
				show: false,
				choosedSpec: '',
				totalPrice: 0,
				quantity: 1,
				id: 0,
				pictures: [],
				swiperWidth: 0,
				swiperHeight: 0,
				id: 0,
				recommendedUser: '',
				exchangeProducts: []
			}
		},
		onLoad(options) {
			// 获取屏幕宽度计算1:1比例尺寸
			const systemInfo = uni.getSystemInfoSync()
			this.swiperWidth = systemInfo.windowWidth
			this.swiperHeight = this.swiperWidth // 保持1:1比例
			if (typeof(options.id) != 'undefined') {
				this.id = options.id
				let token = uni.getStorageSync('api_token')
				if (token == '') {
					this.wxLogin()
				} else {
					this.getProduct()
				}
				if (typeof(options.recommendedUser)) {
					this.recommendedUser = options.recommendedUser
				}
			} else {
				uni.switchTab({
					url: '/pages/product/index'
				})
			}
		},
		onShow() {
		},
		onShareAppMessage(res) {
			let myUser = uni.getStorageSync('myUser')
			return {
				title: this.product.name,
				desc: '华盛咖啡',
				path: `/pages/product/detail?id=${this.product.id}&recommendedUser=${myUser}`,
				imageUrl: this.product.cover
			}
		},
		methods: {
			// 查询可换购的产品
			getExchangeProduct() {
				this.request.get(`api/specifications`, {
					'@filter': `entity.getProduct().getCategory().getType().getSlug() == 'ExchangePurchase' && entity.getRemains() > 0 && entity.getProduct().getIsOnSale() == true`,
					'@expands': "['entity.product.specifications']"
				}).then((res) => {
					console.log('res', res.data)
					let exchangeProducts = []
					for (let i of res.data) {
						this.request.get(`api/products/${i.product.id}`, {
							'@expands': "['entity.specifications']"
						}).then((product) => {
							product.data['quantity'] = 0
							exchangeProducts.push(product.data)
							this.exchangeProducts = exchangeProducts
						})
					}
				})
			},
			wxLogin() {
				let _this = this
				uni.login({
					success(result) {
						let data = {
							code: result.code,
						}
						if (_this.recommendedUser)
							data.recommendedUser = _this.recommendedUser
						_this.request.get(`wechat/mini/login`, data).then((res) => {
							uni.setStorageSync('api_token', res.data.token)
							this.request.get(`api/user`).then((res) => {
								uni.setStorageSync('myUser', res.data.id)
							})
							_this.getProduct()
						})
					}
				})
			},
			getProduct() {
				uni.showLoading()
				this.request.get(`api/products/${this.id}`, {
					'@expands': "['specifications']"
				}).then((res) => {
					console.log(res.data)
					uni.setNavigationBarTitle({
						title: res.data.name
					})
					this.product = res.data
					let pictures = []
					if (res.data.cover) {
						pictures.push(res.data.cover)
					}
					if (res.data.pictures) {
						for (let i of res.data.pictures) {
							pictures.push(i)
						}
					}
					this.pictures = pictures
					this.choosedSpec = res.data.specifications[0]
					this.totalPrice = res.data.specifications[0].__metadata.price
					uni.hideLoading()
				})
				let likeIds = uni.getStorageSync('likeIds')
				if (likeIds != '') {
					for (let i of likeIds) {
						if (i == this.id) {
							this.isFavorite = true
						}
					}
				}
				this.getExchangeProduct()
			},
			shareProduct() {
				uni.shareFileMessage()
			},
			changeQuantity(e) {
				this.quantity = e.value
				let totalPrice = parseInt(e.value) * parseFloat(this.choosedSpec.__metadata.price)
				this.totalPrice = totalPrice.toFixed(2)
			},
			toggleFavorite() {
				let likeIds = uni.getStorageSync('likeIds')
				if (this.isFavorite) {
					likeIds.splice(likeIds.indexOf(this.product.id), 1)
				} else {
					if (likeIds == '') {
						likeIds = [this.product.id]
					} else {
						likeIds.push(this.product.id)
					}
				}
				uni.setStorageSync('likeIds', likeIds)
				this.isFavorite = !this.isFavorite;
				uni.showToast({
					title: this.isFavorite ? '已收藏' : '已取消收藏',
					icon: 'none'
				});

			},
			addCart() {
				let carts = uni.getStorageSync('carts')
				let had = false
				let cart = {
					image: this.product.cover,
					price: this.choosedSpec.__metadata.price,
					id: this.choosedSpec.id,
					quantity: this.quantity,
					selected: false,
					name: this.product.name,
					specification: this.choosedSpec.__metadata.name,
					isAdd: false
				}
				if (carts == '') {
					carts = [cart]
				} else {
					for (let i of carts) {
						if (i.id == cart.id) {
							had = true
						}
					}
					if (had == false) {
						carts.push(cart)
					}
				}
				// 查加购的是否有数量，有的还需要加入去
				for (let i of this.exchangeProducts) {
					let had = false
					if (i.quantity > 0) {
						for (let j of carts) {
							if (i.specifications[0].id == j.id) {
								had = true
							}
						}
						if (had == false) {
							carts.push({
								image: i.cover,
								price: i.specifications[0].__metadata.price,
								id: i.specifications[0].id,
								quantity: i.quantity,
								selected: false,
								name: i.name,
								specification: i.specifications[0].__metadata.name,
								isAdd: true
							})
						}
					}
				}

				uni.setStorageSync('carts', carts)
				uni.showToast({
					title: '加入成功...',
					icon: 'none'
				})
				this.show = false
			},
			toUrl(page) {
				uni.navigateTo({
					url: page
				})
			},
			buyNow() {
				let orderCarts = [{
					image: this.product.cover,
					price: this.choosedSpec.__metadata.price,
					id: this.choosedSpec.id,
					quantity: this.quantity,
					selected: true,
					name: this.product.name,
					specification: this.choosedSpec.__metadata.name
				}]
				// 查加购的是否有数量，有的还需要加入去
				for (let i of this.exchangeProducts) {
					if(i.quantity > 0){
						orderCarts.push({
							image: i.cover,
							price: i.specifications[0].__metadata.price,
							id: i.specifications[0].id,
							quantity: i.quantity,
							selected: false,
							name: i.name,
							specification: i.specifications[0].__metadata.name,
						})
					}
				}
				uni.setStorageSync('orderCarts', orderCarts)
				uni.navigateTo({
					url: '/pages/cart/order'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding-bottom: 100px;
		/* 给底部操作栏留出空间 */
		background-color: #f8f8f8;
	}

	/* 1:1 正方形图片容器 */
	.square-image {
		position: relative;
		width: 100%;
		padding-top: 100%;
		/* 关键属性 */
		overflow: hidden;
		background-color: #f8f8f8;

		.u-image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
		}
	}


	/* 产品信息区域 */
	.info-section {
		padding: 10px;
		background-color: #f3f3f3;
		// background-color: #e64340;
		// background: linear-gradient(90deg, #909399, #bc927a);

		.product-name {
			font-size: 18px;
			font-weight: bold;
			margin-bottom: 12px;
			line-height: 1.4;
			color: #303133;
		}

		.product-price {
			color: #e64340;
			display: flex;
			align-items: baseline;

			.price-symbol {
				font-size: 16px;
				margin-right: 2px;
			}

			.price-number {
				font-size: 24px;
				font-weight: bold;
			}
		}
	}

	/* 产品详情区域 */
	.detail-section {
		// padding: 20px;
		background-color: #fff;
		margin-bottom: 10px;

		.section-title {
			font-size: 16px;
			font-weight: bold;
			margin-bottom: 15px;
			position: relative;
			padding-left: 10px;

			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 3px;
				bottom: 3px;
				width: 4px;
				background-color: #e64340;
				border-radius: 2px;
			}
		}
	}

	/* 底部操作栏 */
	.action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		display: flex;
		align-items: center;
		background-color: #fff;
		border-top: 1px solid #eee;
		padding: 0 10px;
		box-sizing: border-box;
		z-index: 100;

		.action-button {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 12px;
			color: #606266;

			text {
				margin-top: 2px;
			}
		}

		.buy-button {
			flex: 2;
			background: linear-gradient(90deg, #ff9500, #ff5000);
			color: #fff;
			height: 40px;
			border-radius: 20px;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 16px;
			font-weight: bold;
			margin-left: 10px;
		}
	}

	.square-image-container {
		position: relative;
		width: 100%;
		/* 宽度100% */
		padding-top: 100%;
		/* 关键：创建与宽度相等的高度 */
		overflow: hidden;
		background-color: #f8f8f8;
		/* 加载时的背景色 */

		.u-image {
			width: 100vw;
			height: 100vw;
			/* 等于宽度 */
			max-width: 100%;
		}
	}

	.action-button {
		background: transparent;
		padding: 0;
		margin: 0;
		line-height: 1;
	}

	.action-button::after {
		border: none;
	}

	.add-view {
		// height: 50vh;
		border-radius: 10px 10px 0px 0px;
		padding-top: 20px;
		// overflow: auto;
	}

	.activity-item {
		display: flex;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	.product-img {
		width: 150rpx;
		height: 150rpx;
		border-radius: 10rpx;
	}

	.product-info {
		flex: 1;
		margin-left: 20rpx;
	}

	.product-name {
		font-size: 32rpx;
		color: #333;
	}

	.product-price {
		font-size: 35rpx;
		color: #e4393c;
		margin-top: 10rpx;
	}

	.category-name {
		background-color: #18b566;
		font-size: 12px;
		color: #fff;
		padding: 3px 10px;
		border-radius: 5px;
		margin-top: 5px;
	}

	.spec-active {
		margin: 0px 10px;
		padding: 5px 0px;
		background-color: #ff9900;
		color: #fff;
		text-align: center;
		border-radius: 5px;
		border: solid #ff9900 1px;
	}

	.spec {
		margin: 0px 10px;
		padding: 5px 0px;
		color: #ff9900;
		text-align: center;
		border-radius: 5px;
		border: solid #ff9900 1px;
	}

	.price {
		padding-left: 10px;
		color: #e4393c;
		font-size: 23px;
	}

	.swiper-box {
		width: 100%;
		margin: 0 auto;
	}


	.container2 {
		background-color: #f8f8f8;
	}

	.form-table {
		background-color: #ffffff;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	/* 表头样式 */
	.header-row {
		background-color: #2979ff;
		color: white;
		font-weight: bold;
		font-size: 32rpx;
	}

	.header-col {
		padding: 28rpx 20rpx;
		text-align: center;
	}

	/* 数据行通用样式 */
	.data-row {
		border-bottom: 1rpx solid #eee;
	}

	.data-row:last-child {
		border-bottom: none;
	}

	/* 单元格基础样式 */
	.label-cell,
	.value-cell {
		padding: 24rpx 20rpx;
		font-size: 28rpx;
	}

	/* 带背景色的标签列 */
	.bg-cell {
		background-color: #f5f7fa;
		color: #606266;
		font-weight: 500;
	}

	/* 内容列样式 */
	.value-cell {
		color: #303133;
	}

	.e-container {
		padding: 20rpx;
		background-color: #f3f3f3;
	}

	.e-scroll-view {
		width: 100%;
		white-space: nowrap;
	}

	.e-goods-list {
		display: inline-flex;
		padding: 5px;
	}

	.e-goods-item {
		display: flex;
		flex-direction: column;
		width: 30vw;
		background-color: #fff;
		padding: 5px;
		border-radius: 10px;
		margin-right: 20rpx;
		flex-shrink: 0;

		&:last-child {
			margin-right: 0;
		}
	}

	.e-image-container {
		position: relative;
		width: 100%;
		padding-top: 100%;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.e-product-image {
		position: absolute;
		top: 5%;
		left: 5%;
		width: 90%;
		height: 90%;
		border-radius: 10px;
	}

	.e-info {
		display: flex;
		flex-direction: column;
		padding: 15rpx 5rpx;
	}

	.e-name {
		font-size: 26rpx;
		color: #333;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		white-space: normal;
		height: 38px;
		overflow: hidden;
	}

	.e-price {
		font-size: 30rpx;
		color: #e43d33;
		font-weight: bold;
	}
	
	.scroll-container {
	  width: 100%;
	  white-space: nowrap; /* 关键：禁止内容换行 */
	  overflow: hidden;   /* 隐藏溢出内容 */
	}
	
	/* 标签容器 - 使用flex布局强制一行显示 */
	.tag-container {
	  display: flex;         /* 使用flex布局 */
	  flex-wrap: nowrap;     /* 禁止换行 */
	  padding: 10rpx 0;      /* 上下内边距 */
	}
	
	/* 单个标签样式 */
	.tag-item {
	  flex-shrink: 0;        /* 关键：禁止标签缩小 */
	  margin-right: 5px;       /* 左右间距 */
	  white-space: nowrap;   /* 标签内文本不换行 */
	  border-radius: 2px;
	  border: solid #ff9900 1px;
	  color: #ff9900;
	  padding: 0px 5px;
	}
</style>